package com.ironone.streaming;

import java.util.List;
import android.content.Context;
import android.graphics.Bitmap;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SlidingPaneLayout;
import android.support.v4.widget.SlidingPaneLayout.PanelSlideListener;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnFocusChangeListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.ironone.streaming.application.CusAlrtBtnTypes;
import com.ironone.streaming.application.CusAlrtIconTypes;
import com.ironone.streaming.application.CustomAlertDialog;
import com.ironone.streaming.application.FormObject;
import com.ironone.streaming.application.MainApplication;
import com.ironone.streaming.comm.HTTPManager;
import com.ironone.streaming.model.ModelMapper;
import com.ironone.streaming.model.OurShowsDataModel;
import com.ironone.streaming.model.RequestDataModel;
import com.ironone.streaming.model.ResponseDataModel;

public class RequestFragment extends Fragment {
	View view;
	SlidingPaneLayout mPane;
	InputMethodManager imm;

	//Menu btn
	Button btnMenu;	

	//Background overlay image
	ImageView albumart_bg;
	Bitmap bitmap;

	//Form UI
	TextView title_two;
	EditText name, song, artist, dedication;
	Button buttonRequest;
	LinearLayout background_color_layer;


	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);		
		imm = (InputMethodManager)getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
	}

	@Override
	public View onCreateView(LayoutInflater inflater, final ViewGroup container, Bundle savedInstanceState) {
		view = inflater.inflate(R.layout.request_fragment, container, false);

		try {
			mPane = (SlidingPaneLayout) getActivity().findViewById(R.id.pane);
			btnMenu = (Button) view.findViewById(R.id.btnMenu);
			btnMenu.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
					mPane.openPane();
				}
			});

			mPane.setPanelSlideListener(new PanelSlideListener() {
				@Override
				public void onPanelSlide(View arg0, float arg1) {
				}
				@Override
				public void onPanelOpened(View arg0) {
					imm.hideSoftInputFromWindow(arg0.getWindowToken(), 0);
					removeFocusFromEditText();
				}
				@Override
				public void onPanelClosed(View arg0) {
					//imm.hideSoftInputFromWindow(arg0.getWindowToken(), 0);
				}
			});

			//Menu btn
			int supWidth = (int)((FormObject.getInstance().getScreenWidth() * 0.6));
			RelativeLayout.LayoutParams abParam = (RelativeLayout.LayoutParams) btnMenu.getLayoutParams();
			abParam.width = (int)(supWidth - (supWidth * 0.88));
			abParam.height = (int)(supWidth - (supWidth * 0.88));
			btnMenu.setLayoutParams(abParam);

			background_color_layer = (LinearLayout) view.findViewById(R.id.background_color_layer);
			background_color_layer.getBackground().setAlpha(96);
			
			//Background overlay image
			/*bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.bg_frag);
			albumart_bg = (ImageView) view.findViewById(R.id.albumart_bg);
			ViewTreeObserver vto = albumart_bg.getViewTreeObserver();
			vto.addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
				@Override
				public void onGlobalLayout() {
					albumart_bg = (ImageView) view.findViewById(R.id.albumart_bg);
					if(FormObject.getInstance().getAlbumArtImage() == null)
						albumart_bg.setImageBitmap(bitmap);
					else 
						albumart_bg.setImageBitmap(MainApplication.getByteArrToBitmap(FormObject.getInstance().getAlbumArtImage()));

					albumart_bg.setAlpha(64);
				}
			});*/

			//Form UI
			TextView title_one = (TextView) view.findViewById(R.id.title_one);
			title_two = (TextView) view.findViewById(R.id.title_two);
			int size = (int) (FormObject.getInstance().getTextSize());
			title_one.setTextSize(size);
			title_two.setTextSize(size);
			title_two.setSelected(true);

			name = (EditText) view.findViewById(R.id.name);			
			song = (EditText) view.findViewById(R.id.song);
			artist = (EditText) view.findViewById(R.id.artist);
			dedication = (EditText) view.findViewById(R.id.dedication);
			buttonRequest = (Button) view.findViewById(R.id.buttonRequest);
			buttonRequest.setTextSize(FormObject.getInstance().getTextSize());

			view.setOnTouchListener(new OnTouchListener() {

				@Override
				public boolean onTouch(View arg0, MotionEvent arg1) {					
					imm.hideSoftInputFromWindow(arg0.getWindowToken(), 0);
					removeFocusFromEditText();					
					return false;
				}
			});

			buttonRequest.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View arg0) {
					onClick_RequestButton(arg0);					
				}
			});

			editTextValidation();
			getCurrentShowName();

			String msgData = "";
			if(FormObject.getInstance().getTNLId() == null || FormObject.getInstance().getTNLId().equals(""))
				msgData = getString(R.string.please_login_to_continue);
					
			if(title_two.getText().toString().trim().equals(getString(R.string.no_shows_to_request))){
				msgData = getString(R.string.no_shows_to_request);
			}

			if(!msgData.equals("")){
				buttonRequest.setEnabled(false);
								
				CustomAlertDialog alertDialog = new CustomAlertDialog(getActivity(), CusAlrtBtnTypes.OK, CusAlrtIconTypes.WIZERD);
				alertDialog.setTitleText(getActivity().getString(R.string.you_shall_not_pass));
				alertDialog.setMessageText(msgData);			
				alertDialog.show();				
			}
		} catch (Exception e) {
			CustomAlertDialog alertDialog = new CustomAlertDialog(getActivity(), CusAlrtBtnTypes.OK, CusAlrtIconTypes.DUCK);
			alertDialog.setTitleText(getString(R.string.what_the_duck_));
			alertDialog.setMessageText(getString(R.string.something_snapped));			
			alertDialog.show();
		}		
		return view;
	}

	private void editTextValidation(){
		try {
			name.setOnTouchListener(new OnTouchListener() {

				@Override
				public boolean onTouch(View v, MotionEvent event) {
					name.setFocusableInTouchMode(true);
					return false;
				}
			});
			name.setOnFocusChangeListener(new OnFocusChangeListener() {

				@Override
				public void onFocusChange(View v, boolean hasFocus) {
					if (hasFocus) return;					
					nameValidation();
				}
			});

			song.setOnTouchListener(new OnTouchListener() {

				@Override
				public boolean onTouch(View v, MotionEvent event) {
					song.setFocusableInTouchMode(true);
					return false;
				}
			});
			song.setOnFocusChangeListener(new OnFocusChangeListener() {

				@Override
				public void onFocusChange(View v, boolean hasFocus) {
					if (hasFocus) return;					
					songValidation();
				}
			});

			artist.setOnTouchListener(new OnTouchListener() {

				@Override
				public boolean onTouch(View v, MotionEvent event) {
					artist.setFocusableInTouchMode(true);
					return false;
				}
			});
			artist.setOnFocusChangeListener(new OnFocusChangeListener() {

				@Override
				public void onFocusChange(View v, boolean hasFocus) {
					if (hasFocus) return;					
					artistValidation();
				}
			});


			dedication.setOnTouchListener(new OnTouchListener() {

				@Override
				public boolean onTouch(View v, MotionEvent event) {
					dedication.setFocusableInTouchMode(true);
					return false;
				}
			});
			dedication.setOnFocusChangeListener(new OnFocusChangeListener() {

				@Override
				public void onFocusChange(View v, boolean hasFocus) {
					if (hasFocus) return;					
					dedicationValidation();
				}
			});
		} catch (Exception e) {
			CustomAlertDialog alertDialog = new CustomAlertDialog(getActivity(), CusAlrtBtnTypes.OK, CusAlrtIconTypes.DUCK);
			alertDialog.setTitleText(getString(R.string.what_the_duck_));
			alertDialog.setMessageText(getString(R.string.something_snapped));			
			alertDialog.show();
		}
	}


	private boolean nameValidation(){
		if(name.getText().toString().equals("")){
			name.setError(getActivity().getString(R.string.name_cannot_be_empty));
			return false;
		}

		if(name.getText().toString().matches(".*\\d.*")){
			name.setError(getActivity().getString(R.string.name_has_invalid_characters));
			return false;
		}

		name.setError(null);
		return true;
	}

	private boolean songValidation(){
		if(song.getText().toString().equals("")){
			song.setError(getActivity().getString(R.string.song_cannot_be_empty));
			return false;
		}
		else{
			song.setError(null);
			return true;
		}
	}

	private boolean artistValidation(){
		if(artist.getText().toString().equals("")){
			artist.setError(getActivity().getString(R.string.artist_cannot_be_empty));
			return false;
		}
		else{
			artist.setError(null);
			return true;
		}
	}

	private boolean dedicationValidation(){
		if(dedication.getText().toString().equals("")){
			dedication.setError(getActivity().getString(R.string.dedication_cannot_be_empty));
			return false;
		}
		else{
			dedication.setError(null);
			return true;
		}
	}

	private void getCurrentShowName(){
		List<OurShowsDataModel> showModel = FormObject.getInstance().getShowsData();
		int currTime = FormObject.getInstance().getTime();
		int dayX = MainApplication.getDayIndex();

		for(int x=0; x < showModel.size(); x++) {			
			// if show is not casting on today it will be ignored
			if(!showModel.get(x).showDays[dayX]) continue;
			
			if(showModel.get(x).showtime_start <= currTime && showModel.get(x).showtime_end >= currTime){
				title_two.setText(showModel.get(x).showName);
				break;
			}
		}
	}

	private void removeFocusFromEditText(){
		name.setFocusable(false);
		song.setFocusable(false);
		artist.setFocusable(false);
		dedication.setFocusable(false);
	}

	private void onClick_RequestButton(View arg0) {
		try {
			boolean namVal = nameValidation();
			boolean sonVal = songValidation();
			boolean artVal = artistValidation();
			boolean dedVal = dedicationValidation();

			removeFocusFromEditText();

			if(namVal && sonVal && artVal && dedVal){
				RequestDataModel rdm = new RequestDataModel();
				rdm.showName = title_two.getText().toString();
				rdm.reqesterName = name.getText().toString().trim(); 
				rdm.songName = song.getText().toString().trim();
				rdm.artist = artist.getText().toString().trim();
				rdm.dedication = dedication.getText().toString().trim();

				FormObject.getInstance().setIsSlidingPaneLayoutSlidable(false);
				btnMenu.setVisibility(View.INVISIBLE);
				buttonRequest.setText(R.string.please_wait_);
				buttonRequest.setEnabled(false);
				btnMenu.setVisibility(View.GONE);
				new RequestAsync().execute(rdm);
			}
		} catch (Exception e) {
			CustomAlertDialog alertDialog = new CustomAlertDialog(getActivity(), CusAlrtBtnTypes.OK, CusAlrtIconTypes.BIRD);
			alertDialog.setTitleText(getString(R.string.pigeon_s_taken_an_arrow));
			alertDialog.setMessageText(getActivity().getString(R.string.error_sending_details));			
			alertDialog.show();
		}
	}

	public class RequestAsync extends AsyncTask<Object, Void, String> {

		@Override
		protected String doInBackground(Object... arg0) {
			try {
				RequestDataModel rdm = (RequestDataModel) arg0[0];
				HTTPManager httpmanager = new HTTPManager(getActivity());
				ResponseDataModel responseModel = httpmanager.sendRequestData(rdm);

				if(responseModel.isError && responseModel.responseData == null){
					return responseModel.errorMessage;
				}

				String data = ModelMapper.getRequestResponseStatus(responseModel);
				if(data == null){
					return getString(R.string.error_jsonexception);
				}/*else if (data.equals("")){
					return getString(R.string.data_sent_successfully);
				}*/
				else{
					return data;
				}
			} catch (Exception e) {
				return getString(R.string.error_general);
			}
		}

		@Override
		protected void onPostExecute(String result) {
			super.onPostExecute(result);

			FormObject.getInstance().setIsSlidingPaneLayoutSlidable(true);
			btnMenu.setVisibility(View.VISIBLE);
			buttonRequest.setText(getString(R.string.request));
			buttonRequest.setEnabled(true);
			btnMenu.setVisibility(View.VISIBLE);

			CustomAlertDialog alertDialog;
			if(result.toLowerCase().contains("request sent")){
				alertDialog = new CustomAlertDialog(getActivity(), CusAlrtBtnTypes.OK, CusAlrtIconTypes.SUCCESS);
				alertDialog.setTitleText(getString(R.string.success_text));
				alertDialog.setMessageText(getString(R.string.request_successful));
				
				name.setText("");
				song.setText("");
				artist.setText("");
				dedication.setText("");
			}else{
				alertDialog = new CustomAlertDialog(getActivity(), CusAlrtBtnTypes.OK, CusAlrtIconTypes.WIZERD);
				alertDialog.setTitleText(getString(R.string.you_shall_not_pass));
				alertDialog.setMessageText(result);
			}
			
			alertDialog.show();
		}
	}
}